﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;

using HelfenHelfen.DataAccess.Interfaces;
using HelfenHelfen.DataAccess.Factories;

namespace HelfenHelfen.Web.Forms.Site {
   public class ShowImage : IHttpHandler {
      public void ProcessRequest(HttpContext context) {
         Guid demandGUID = Guid.Empty;

         if (context.Request.QueryString["id"] != null)
            demandGUID = Guid.ParseExact(context.Request.QueryString["id"], "D" );

         context.Response.ContentType = "image/jpeg";
         Stream strm = null;
         IImageDataAccess da = DataAccessFactory.CreateImageDataAccess();
         var img = da.GetByDemand(demandGUID);
         if(img != null){
            strm = new MemoryStream(img.ImageData);
         } else {
            MemoryStream memStream = new MemoryStream();
            string path = context.Server.MapPath("~/img/Default.jpg");
            Bitmap objBitmap = new Bitmap(path);
            objBitmap.Save(memStream, ImageFormat.Jpeg);
            objBitmap.Dispose();
            memStream.Seek(0L, SeekOrigin.Begin);
            strm = memStream;
         }

         byte[] buffer = new byte[4096];
         int byteSeq = strm.Read(buffer, 0, 4096);

         while (byteSeq > 0) {
            context.Response.OutputStream.Write(buffer, 0, byteSeq);
            byteSeq = strm.Read(buffer, 0, 4096);
         }
         context.Response.BinaryWrite(buffer);
      }


      public bool IsReusable {
         get {
            return false;
         }
      }
   }
}